// Windows/FileMapping.h

#ifndef __WINDOWS_FILEMAPPING_H
#define __WINDOWS_FILEMAPPING_H

#include "Common/System/Threading/Thread.h"

namespace Common {
namespace FileSystem {

class CFileMapping: public  System::Threading::CHandle
{
public:
  DWORD Create(DWORD protect, UINT64 maxSize, LPCTSTR name)
  {
    m_hHandle = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, protect, (DWORD)(maxSize >> 32), (DWORD)maxSize, name);
    return ::GetLastError();
  }

  DWORD Open(DWORD desiredAccess, LPCTSTR name)
  {
    m_hHandle = ::OpenFileMapping(desiredAccess, FALSE, name);
    if (m_hHandle != 0)
      return 0;
    return ::GetLastError();
  }

  LPVOID Map(DWORD desiredAccess, UINT64 fileOffset, SIZE_T numberOfBytesToMap)
  {
    return ::MapViewOfFile(m_hHandle, desiredAccess, (DWORD)(fileOffset >> 32), (DWORD)fileOffset, numberOfBytesToMap);
  }

  LPVOID Map(DWORD desiredAccess, UINT64 fileOffset, SIZE_T numberOfBytesToMap, LPVOID baseAddress)
  {
    return ::MapViewOfFileEx(m_hHandle, desiredAccess, (DWORD)(fileOffset >> 32), (DWORD)fileOffset, numberOfBytesToMap, baseAddress);
  }
};

class CFileUnmapper
{
  const void *_data;
public:
  CFileUnmapper(const void *data) : _data(data) {}
  ~CFileUnmapper() { ::UnmapViewOfFile(_data); }
};

}
}
#endif
